let express = require("express");

//实例化
let app = express();
//开启静态资源服务器
app.use(express.static("./"));

//把这个路由配置放在所有路由的前面，方便调用next操作
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length, Authorization,Accept,X-Requested-With"
  );
  res.header(
    "Access-Control-Allow-Methods",
    "PUT,PATCH,POST,GET,DELETE,OPTIONS"
  );

  // 跨域请求CORS中的预请求
  if (req.method == "OPTIONS") {
    res.sendStatus(200); /*让options请求快速返回*/
  } else {
    next();
  }
});

//jsonp
let data = require("./data.json");
app.get("/jsonp", (req, res) => {
  let { callback } = req.query;
  let str = JSON.stringify(data);
  res.send(`${callback}(${str})`);
});

//cors
// let arr = ['http://localhost:3001','http://localhost:3002','http://localhost:3003'];//白名单设置
app.get("/cors", (req, res) => {
  res.header("Access-Control-Allow-Origin", "*"); //* 代表所有的域名都能访问我的这个接口
  res.send(data);
});

//服务器代理

//开启服务 端口号：1000-60000
app.listen(2005, () => {
  console.log("服务器已开启，请访问：http://localhost:2005");
});
